package cn.tedu.order.service;

import cn.tedu.order.entity.Order;
import cn.tedu.order.feign.AccountClient;
import cn.tedu.order.feign.EasyIdClient;
import cn.tedu.order.feign.StorageClient;
import cn.tedu.order.mapper.OrderMapper;
import cn.tedu.order.util.JsonUtil;
import cn.tedu.order.util.RedisUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.SortParameters;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private StorageClient storageClient;
    @Autowired
    private AccountClient accountClient;
    @Autowired
    private RedisUtil redisUtil;

    @Transactional  //控制本地事务
    @GlobalTransactional  //开启全局事务，只在第一个模块添加
    @Override
    public void create(Order order) {
        // 远程调用发号器生成订单id
        String s = easyIdClient.nextId("order_business");
        Long orderId = Long.valueOf(s);

        order.setId(orderId);

        orderMapper.create(order);

        // 远程调用库存减少商品库存
        storageClient.decrease(order.getProductId(), order.getCount());
        // 远程调用账户扣减账户金额
        accountClient.decrease(order.getUserId(), order.getMoney());

        // 向redis存入订单缓存数据
        redisUtil.set(""+orderId, JsonUtil.to(order));
    }

    @Override
    public Order findById(Long id) {

        String json = (String) redisUtil.get("" + id);
        if (json != null) {
            return JsonUtil.from(json, Order.class);
        }

        Order order = orderMapper.selectById(id);
        redisUtil.set(""+id, JsonUtil.to(order));

        return order;
    }
}
